#!/usr/bin/env bash

# ===== 代理配置（可按需修改） =====
PROXY_HOST="127.0.0.1"
HTTP_PROXY_PORT="10808"   # 供 http_proxy 与 https_proxy 使用
SOCKS5_PROXY_PORT="10808" # 供 all_proxy（socks5）使用
# NO_PROXY 示例：.local,localhost,127.0.0.1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16
NO_PROXY=""
# ===========================================

usage() {
  cat <<'EOF'
用法：source set_proxy_v2ray.sh [on|off|status|toggle]

子命令：
  on       按当前配置开启代理
  off      关闭（清除）所有相关代理环境变量
  status   显示当前代理相关环境变量
  toggle   根据当前状态在开启/关闭之间切换

说明：请使用 `source set_proxy_v2ray.sh <子命令>` 以便对当前 shell 生效。
EOF
}

compose_urls() {
  HTTP_PROXY_URL="http://${PROXY_HOST}:${HTTP_PROXY_PORT}"
  HTTPS_PROXY_URL="${HTTP_PROXY_URL}"
  SOCKS5_PROXY_URL="socks5://${PROXY_HOST}:${SOCKS5_PROXY_PORT}"
}

enable_proxy() {
  compose_urls

  export http_proxy="${HTTP_PROXY_URL}"
  export https_proxy="${HTTPS_PROXY_URL}"
  export all_proxy="${SOCKS5_PROXY_URL}"

  export HTTP_PROXY="${HTTP_PROXY_URL}"
  export HTTPS_PROXY="${HTTPS_PROXY_URL}"
  export ALL_PROXY="${SOCKS5_PROXY_URL}"

  if [ -n "${NO_PROXY}" ]; then
    export no_proxy="${NO_PROXY}"
    export NO_PROXY="${NO_PROXY}"
  fi

  printf "已开启代理：\n"
  printf "  http_proxy=%s\n" "$http_proxy"
  printf "  https_proxy=%s\n" "$https_proxy"
  printf "  all_proxy=%s\n" "$all_proxy"
  if [ -n "${no_proxy-}" ]; then
    printf "  no_proxy=%s\n" "$no_proxy"
  fi
}

disable_proxy() {
  unset http_proxy https_proxy all_proxy HTTP_PROXY HTTPS_PROXY ALL_PROXY no_proxy NO_PROXY
  printf "已关闭代理。\n"
}

show_status() {
  printf "当前代理状态：\n"
  printf "  http_proxy=%s\n" "${http_proxy-}"
  printf "  https_proxy=%s\n" "${https_proxy-}"
  printf "  all_proxy=%s\n" "${all_proxy-}"
  printf "  no_proxy=%s\n" "${no_proxy-}"
  printf "  HTTP_PROXY=%s\n" "${HTTP_PROXY-}"
  printf "  HTTPS_PROXY=%s\n" "${HTTPS_PROXY-}"
  printf "  ALL_PROXY=%s\n" "${ALL_PROXY-}"
  printf "  NO_PROXY=%s\n" "${NO_PROXY-}"
}

is_enabled() {
  [ -n "${http_proxy-}" ] || [ -n "${HTTP_PROXY-}" ]
}

toggle_proxy() {
  if is_enabled; then
    disable_proxy
  else
    enable_proxy
  fi
}

main() {
  cmd="${1-}"
  case "$cmd" in
    on)
      enable_proxy ;;
    off)
      disable_proxy ;;
    status)
      show_status ;;
    toggle)
      toggle_proxy ;;
    "")
      usage ;;
    *)
      printf "未知子命令：%s\n\n" "$cmd" >&2
      usage
      return 1 ;;
  esac

  if [ "${BASH_SOURCE[0]-$0}" = "$0" ]; then
    printf "\n提示：请使用 'source %s %s' 以便对当前 shell 生效。\n" "$0" "$cmd"
  fi
}

main "$@"

